package com.dnb.webmash.playmaker.server;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ServerFieldVerifier {
	public static boolean isValidURL(String s) {
		return Pattern.matches("((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\\w\\d:#@%/;$()~_\\?\\+-=\\\\.&]*)",s);
	}

	//TODO TEST THE CLIENTFIELDVERIFIER VERSION OF THIS
	//returns the www.domain.ext/ of a url without anything after the ending forward slash
	public static String getBaseDomain(String s){
		String result="";
		Pattern pattern = Pattern.compile("((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[^/\"\' ]+)");
        Matcher matcher = pattern.matcher(s);			        			       	        
        while (matcher.find()) {result += matcher.group(0);}
        return result.trim();
	}
	
	public static String getFirstSubDir(String s){//input is not MyURL but internal link ex. /videos/cat/1123/movie1234.html
		Pattern pattern = Pattern.compile("(/)[^/\"\']+"); //TODO consider further segmenting using other known MyURL dividers like & or #
        Matcher matcher = pattern.matcher(s);			        			       	        
        if (matcher.find()) return matcher.group(0).trim(); //returns '/videos' (ex above)
        else return "";
	}
	
	public static String trimToLastSlash(String s){
		Pattern pattern = Pattern.compile("[^\"\'\n ]+/");
		Matcher matcher = pattern.matcher(s);			        			       	        
        if (matcher.find()) return matcher.group(0).trim();
        else return "";
	}
	//gets rid of any arguments at the end of a url
	public static String cleanURL(String s){
		Pattern pattern = Pattern.compile("[^\"\'\n&\\?#= ]+");
		Matcher matcher = pattern.matcher(s);			        			       	        
        if (matcher.find()) return matcher.group(0).trim();
        else return "";
	}
}
